<template>
  <div class="login_account">
    <el-form label-width="80px" :rules="rules" :model="account" ref="formRef" status-icon>
      <el-form-item label="Username" prop="user_name">
        <el-input v-model="account.user_name" />
      </el-form-item>
      <el-form-item label="Password" prop="user_pwd">
        <el-input v-model="account.user_pwd" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, defineExpose } from 'vue'
import { useStore } from 'vuex'
import { ElForm } from 'element-plus'
import localCache from '@/utils/cache'

import { rules } from '../config/account-config'

const store = useStore()

const account = reactive({
  user_name: localCache.getCache('user_name') ?? '',
  user_pwd: localCache.getCache('user_pwd') ?? ''
  // user_name: '',
  // user_pwd: ''
})

const formRef = ref<InstanceType<typeof ElForm>>()

const loginAction = (isKeepPassword: boolean) => {
  // console.log('1111')
  // console.log(isKeepPassword)
  // store.dispatch('login/accountLoginAction', { ...account })
  if (isKeepPassword) {
    // 本地缓存
    localCache.setCache('user_name', account.user_name)
    localCache.setCache('user_pwd', account.user_pwd)
  }
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      // 1.判断是否需要记住密码
      if (isKeepPassword) {
        // 本地缓存
        localCache.setCache('user_name', account.user_name)
        localCache.setCache('user_pwd', account.user_pwd)
      } else {
        localCache.deleteCache('user_name')
        localCache.deleteCache('user_pwd')
      }
      // 2.开始进行登录验证
      store.dispatch('login/accountLoginAction', { ...account })
    }
  })
}

defineExpose({
  loginAction
})
</script>

<style scoped></style>
